package com.nus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.nus.parsers.ParserAPIs;
import com.nus.representations.IvleModule;
import com.nus.representations.IvleModuleAnnouncements;

public class IvleModuleAnnouncementActivity extends Activity {
	private ListView lv;

	private String lv_arr[];

	private ArrayList<IvleModuleAnnouncements> announcements;
	public static String ANNOUNCEMENT_TITLE;
	public static String ANNOUNCEMENT_DESCRIPTION;
	public static String ANNOUNCEMENT_DATE;
	public static String ANNOUNCEMENT_CREATORNAME;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ivleannouncementslayout);

		String url = "https://ivle.nus.edu.sg/api/Lapi.svc/Announcements?APIKey=W7RtgW7GZKUpaEkJ1NwUD&AuthToken="
				+ NUS_Android.IVLE_Token
				+ "&CourseID="
				+ IvleModuleActivity.COURSE_ID
				+ "&Duration=0&TitleOnly=false&output=json";
		try {
			String response = getResponseText(url);

			Log.i("Response", response);

			announcements = ParserAPIs.parseIvleModuleAnnouncements(response);

			Log.i("rohitSize", announcements.size() + "");
			lv_arr = new String[announcements.size()];
			for (int i = 0; i < announcements.size(); i++) {
				// Log.i("rohitID",news.get(i).getID());
				Log.i("rohitTitle", announcements.get(i).getTitle());
				lv_arr[i] = announcements.get(i).getTitle();
				Log.i("rohitTitle", " value of lv_arr is"
						+ announcements.get(i).getTitle());
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			// System.out.println(" throwing exception here ");
			e.printStackTrace();
		}

		lv = (ListView) findViewById(R.id.announcementsLV);

		lv.setAdapter(new ListAdapter(IvleModuleAnnouncementActivity.this,
				R.id.announcement_item, announcements));
	}

	private class ListAdapter extends ArrayAdapter<IvleModuleAnnouncements> { // --
		// CloneChangeRequired
		private ArrayList<IvleModuleAnnouncements> mList; // --CloneChangeRequired
		private Context mContext;

		public ListAdapter(Context context, int textViewResourceId,
				ArrayList<IvleModuleAnnouncements> list) { // --CloneChangeRequired
			super(context, textViewResourceId, list);
			this.mList = list;
			this.mContext = context;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			try {
				if (view == null) {
					LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					view = vi.inflate(R.layout.ivleannouncementsitem, null);
				}
				final IvleModuleAnnouncements listItem = mList.get(position);
				if (listItem != null) {
					// setting list_item views
					TextView tv = (TextView) view
							.findViewById(R.id.announcement_title);
					tv.setText(listItem.getTitle());
					TextView tv2 = (TextView) view
							.findViewById(R.id.created_date);
					//tv2.setTextColor(Color.BLUE);
					tv2.setText(listItem.getCreatedDate());

					view.setOnClickListener(new OnClickListener() {
						public void onClick(View arg0) { // --clickOnListItem
							
							arg0.refreshDrawableState();
							Intent myIntent = new Intent(
									IvleModuleAnnouncementActivity.this,
									IvleModuleAnnoucementDescriptionActivity.class);
							ANNOUNCEMENT_TITLE = listItem.getTitle();
							ANNOUNCEMENT_DESCRIPTION = listItem
									.getDescription();
							ANNOUNCEMENT_CREATORNAME = listItem
									.getCreatorName();
							ANNOUNCEMENT_DATE = listItem.getCreatedDate();
							startActivity(myIntent);
							arg0.setBackgroundColor(Color.parseColor("#191919"));
						}
					});
                        view.setOnTouchListener(new OnTouchListener() {
						
						public boolean onTouch(View v, MotionEvent event) {
							// TODO Auto-generated method stub
							Log.i("time on touch", event.getDownTime()+"");
							v.setBackgroundColor(Color.BLUE);
							return false;
						}
					});
				}
			} catch (Exception e) {
				Log.i(IvleModuleAnnouncementActivity.ListAdapter.class
						.toString(), e.getMessage());
			}
			return view;
		}
	}

	// lv.setOnItemClickListener(new OnItemClickListener() {
	//
	// public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
	// long arg3) {
	//
	//
	// Log.i("lv.getItemIdAtPosition(arg2)","item clicked"+lv.getItemIdAtPosition(arg2)+" "+arg3);
	// int id=(int)lv.getItemIdAtPosition(arg2);
	// Log.i(" announcemnts","title"+announcements.get(id).getTitle());
	// Log.i(" announcements","description"+announcements.get(id).getDescription());
	// Log.i(" announcements","created name"+announcements.get(id).getCreatorName());
	// Log.i(" announcemnets","created date"+announcements.get(id).getCreatedDate());
	// ANNOUNCEMENT_TITLE=announcements.get(id).getTitle();
	// ANNOUNCEMENT_DESCRIPTION=announcements.get(id).getDescription();
	// ANNOUNCEMENT_CREATORNAME= announcements.get(id).getCreatorName();
	// ANNOUNCEMENT_DATE=announcements.get(id).getCreatedDate();
	// startActivity(new
	// Intent("com.nus.IvleModuleAnnoucementDescriptionActivity"));
	//
	// }
	//
	// });
	//
	// lv.setAdapter(new
	// ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
	//
	// }
	public String getResponseText(String stringUrl) throws IOException {
		StringBuilder response = new StringBuilder();

		URL url = new URL(stringUrl);
		HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
		if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			BufferedReader input = new BufferedReader(new InputStreamReader(
					httpconn.getInputStream()), 8192);
			String strLine = null;
			while ((strLine = input.readLine()) != null) {
				response.append(strLine);
			}
			input.close();
		}
		return response.toString();
	}

}